/**
 * 导航栏菜单
 * 最多三层
 * @author Canaan
 * @date 2019/3/7 11:19
 */
export default {

    state: {
        navMenu: []
    },

    getters: {
        navMenu: (state) => {
            let role = state.userContext.role;
            if (!role) {
                return [];
            }

            //进行深拷贝
            let navMenu = JSON.parse(JSON.stringify(state.navMenu));

            //权限过滤
            function authFilter(data) {
                if (!data || !(data instanceof Array) || data.length === 0) {
                    return false;
                }
                return data.indexOf(role) !== -1;
            }

            //递归过滤子节点
            function subFiler(item) {
                if (!item.subs || !(item.subs instanceof Array) || item.subs.length === 0) {
                    return null; //子节点不存在
                }

                let arr = item.subs.filter(subItem => {
                    return authFilter(subItem.auth);
                });

                for (let arrElement of arr) {
                    arrElement.subs = subFiler(arrElement);
                }

                return arr;
            }

            return navMenu.filter(item => {
                //过滤权限
                let flag = authFilter(item.auth);
                if (!flag) {
                    return flag;
                }

                //过滤子节点
                if (!item.subs || !(item.subs instanceof Array) || item.subs.length === 0) {
                    return flag; //子节点不存在
                }

                item.subs = subFiler(item);

                return flag;
            });

        }
    },

    mutations: {
        navMenu(state, loginNavMenu) {
            state.navMenu = loginNavMenu;
        }
    },

    actions: {
        loadNavMenu({commit, state}, vue) {
            //sessionStorage 没有token 那么不加载
            const token = sessionStorage.getItem(vue.$env.LOGIN_TOKEN);
            if (!token) {
                return;
            }

            return vue.$ajax.get('auth/current_view')
                .then(res => {
                    if (res.code !== 0) {
                        throw res.msg;
                    }
                    debugger
                    let data = [{"icon":"iconfont iconai-home xy-nav-icon","id":6,"menuCode":"index","name":"系统首页","rank":1,"type":"NAV_BAR"},{"icon":"iconfont iconicopowerset xy-nav-icon xy-nav-icon-md","id":16,"menuCode":"systemMgr","name":"系统设置","rank":50,"subs":[{"icon":"iconfont iconanquan1 xy-nav-icon xy-nav-icon-gl","id":26,"menuCode":"roleViewIndex","name":"权限配置","rank":2,"type":"NAV_BAR"},{"icon":"iconfont iconmanage_fill xy-nav-icon xy-nav-icon-md","id":18,"menuCode":"viewWidgetIndex","name":"模块管理","rank":4,"type":"NAV_BAR"}],"type":"NAV_BAR"}];
                    // commit('navMenu', res.data);
                    commit('navMenu', data);
                    return res.data;
                });
        }
    }

}